<template>
  <div>
    <el-dialog class="dialog" :visible.sync="visible" :width="width" :modal-append-to-body="false" :show-close="true"
      :close-on-click-modal="false" :before-close="hide" :style="{ '--el-dialog-height': height }">
      <template slot="title">
        <div class="close" @click="hide"></div>
        <div class="dialog-header">
          <div class="header-title">{{ params.id ? '修改' : '新增' }} 场地</div>
        </div>
      </template>
      <div class="dialog-body" v-loading="dataLoading">
        <div class="form-box">
          <el-form ref="formRef" class="formStyle" :model="form" :rules="formRules" label-width="85px"
            @submit.native.prevent>
            <el-form-item label="场地名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入场地" :spellcheck="false" />
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型">
                <el-option v-for="item in typeList" :key="item.label" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="封面" prop="imageUrl">
              <el-upload el-upload ref="coverImageUploadRef" class="upload" action="#" with-credentials
                :auto-upload="true" list-type="picture-card" :limit="1" :file-list="coverImageList"
                accept=".jpg,.jpeg,.png" :http-request="handleFileUpload" :on-remove="handleCoverImageRemove"
                :on-change="handleCoverImageChange" :on-exceed="handleExceed" :on-success="handleCoverImageSuccess">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="地址" prop="location">
              <el-input v-model="form.location" type="textarea" placeholder="请输入地址" :spellcheck="false" :rows="2"
                resize="none" />
            </el-form-item>
            <el-form-item label="容纳人数" prop="capacity">
              <el-input-number v-model="form.capacity" placeholder="请输入容纳人数" :min="1" controls-position="right"
                :spellcheck="false" />
            </el-form-item>
            <el-form-item label="场地面积" prop="area">
              <el-input-number v-model="form.area" placeholder="请输入场地面积" :min="1" controls-position="right"
                :spellcheck="false" />
              M²
            </el-form-item>
            <el-form-item label="场地布局图" prop="layoutImageUrl">
              <el-upload el-upload ref="layoutImageUploadRef" class="upload" action="#" with-credentials
                :auto-upload="true" list-type="picture-card" :limit="1" :file-list="layoutImageList"
                accept=".jpg,.jpeg,.png" :http-request="handleFileUpload" :on-remove="handleLayoutImageRemove"
                :on-change="handleLayoutImageChange" :on-exceed="handleExceed" :on-success="handleLayoutImageSuccess">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="开放时间" prop="openTimePeriod">
              <el-time-picker is-range v-model="timeArr" range-separator="至" start-placeholder="开始时间"
                end-placeholder="结束时间" placeholder="选择时间范围" format="HH:mm" value-format="HH:mm" />
            </el-form-item>
            <el-form-item label="时长" prop="minBookingUnit">
              <el-input-number v-model="form.minBookingUnit" placeholder="请输入时长" :min="1" controls-position="right"
                :spellcheck="false" />
              分钟
            </el-form-item>
            <el-form-item label="最大数量" prop="maxNum">
              <el-input-number v-model="form.maxNum" placeholder="请输入最大数量" :min="1" controls-position="right"
                :spellcheck="false" />
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入描述" :spellcheck="false" :rows="3"
                resize="none" />
            </el-form-item>
            <el-form-item label="开放状态" prop="status">
              <el-switch v-model="form.status" :active-value="'enabled'" :inactive-value="'disabled'" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hide">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getFileNameFromURL } from '@/utils/index.js';
import * as api from '@/api/bookingManger/index.js';
import * as dictApi from '@/api/system/dict/data.js';
import * as fileApi from '@/api/file/index.js';

export default {
  name: 'BookFieldEditDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    params: {
      type: Object,
      default: {},
    },
    width: {
      type: String,
      default: '80%',
    },
    height: {
      type: String,
      default: '915px',
    },
  },
  data() {
    return {
      dataLoading: false,
      form: {},
      formRules: {
        name: [{ required: true, trigger: 'blur', message: '请输入场地名称' }],
        type: [{ required: true, trigger: 'blur', message: '请选择类型' }],
        startTime: [{ required: true, trigger: 'blur', message: '请选择领取时间' }],
        description: [{ required: true, trigger: 'blur', message: '请输入描述' }],
      },
      timeArr: null,
      coverImageList: [],
      layoutImageList: [],
      typeList: [],
    };
  },
  watch: {
    visible: {
      handler(value) {
        if (value) {
          this.form = this.getForm();
          this.getData();
        }
      },
      immediate: true,
    },
    timeArr: {
      handler(value) {
        if (value) this.form.openTimePeriod = value.join('-');
      },
    },
  },
  methods: {
    hide() {
      this.resetForm();
      this.$emit('update:visible', false);
    },
    resetForm() {
      this.form = this.getForm();
      this.coverImageList = [];
      this.layoutImageList = [];
      this.timeArr = null;
    },
    getForm() {
      let form = {
        name: '',
        type: '',
        imageUrl: '',
        location: '',
        capacity: undefined,
        area: undefined,
        layoutImageUrl: '',
        minBookingUnit: undefined,
        openTimePeriod: null,
        maxNum: 1,
        description: '',
        status: 'enabled',
      };
      return form;
    },
    async getData() {
      if (!this.params.id) return;
      this.dataLoading = true;
      const { data } = await api.getBookFieldInfo(this.params.id);
      Object.keys(this.form).forEach((key) => {
        if (data[key] !== undefined) this.form[key] = data[key];
      });
      this.coverImageList = [{ name: getFileNameFromURL(this.form.imageUrl), url: this.form.imageUrl }];
      this.layoutImageList = [{ name: getFileNameFromURL(this.form.layoutImageUrl), url: this.form.layoutImageUrl }];
      this.timeArr = this.form.openTimePeriod.split('-');
      const { data: dictData } = await dictApi.getDicts('book_field_type');
      this.typeList = dictData.map((dict) => {
        return { label: dict.dictLabel, value: dict.dictValue };
      });
      this.dataLoading = false;
    },
    // 移除封面时
    handleCoverImageRemove(file, fileList) {
      this.coverImageList = fileList;
    },
    // 封面状态改变
    handleCoverImageChange(file, fileList) {
      if (file.status == 'ready') {
        this.coverImageList = fileList;
      }
    },
    // 移除场地布局图时
    handleLayoutImageRemove(file, fileList) {
      this.layoutImageList = fileList;
    },
    // 场地布局图状态改变
    handleLayoutImageChange(file, fileList) {
      if (file.status == 'ready') {
        this.layoutImageList = fileList;
      }
    },
    // 当超出限制时
    handleExceed(files, fileList) {
      this.$message.warning({
        message: `当前限制选择 1 个图片，已经选择了 ${fileList.length} 个图片`,
      });
    },
    // 上传文件方法
    async handleFileUpload(param) {
      const formData = new FormData();
      formData.append('file', param.file);
      try {
        const data = await fileApi.uploadPictureMinio(formData);
        param.onSuccess(data);
      } catch (error) {
        console.log('error', error);
        param.onError();
      }
    },
    // 上传文件成功
    async handleCoverImageSuccess(data, file, file_list) {
      if (!data) return;
      this.form.imageUrl = data.url;
    },
    // 上传文件成功
    async handleLayoutImageSuccess(data, file, file_list) {
      if (!data) return;
      this.form.layoutImageUrl = data.url;
    },
    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;
        try {
          const text = this.params.id ? `是否确定修改？` : `是否确定新增`;
          await this.$confirm(text, '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          });
          for (const key in this.form) {
            if (typeof this.form[key] == 'undefined') this.form[key] = '';
          }
          // 提交表单
          let funcName = '';
          if (this.params.id) {
            funcName = 'editBookField';
            this.form.id = this.params.id;
          } else {
            funcName = 'addBookField';
          }
          const res = await api[funcName]({ ...this.form });
          this.$message.success({ message: res.msg });
          this.$emit('success', 'BookFieldEditDialog');
          this.hide();
        } catch (error) {
          console.log('error', error);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/dialog.scss';
// @import '@/assets/styles/mixin.scss';

// ::v-deep .el-dialog__body {
//   padding-right: 5px !important;
// }

.dialog-body {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.formStyle {
  // @include el-form-style;
  ::v-deep .el-form-item {
    width: 100%;
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0px;
      // .el-form-item__content {
      //   text-align: center;
      // }
    }

    // .el-input-number {
    //   width: auto !important;
    // }

    .unit {
      margin-left: 10px;
    }
    .el-upload-list--picture-card .el-upload-list__item {
      width: 222px;
      height: auto;
      line-height: 1;
    }
  }
}
</style>
